﻿using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Management;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace WeishaLearningSystemRegester
{
    internal class LicenseGenerator
    {
        private GenerateConfig _config;

        private int _freeTime = 3;

        // Token: 0x0400001A RID: 26
        private DateTime StartTime;

        // Token: 0x0400001B RID: 27
        private DateTime EndTime;

        // Token: 0x0400001C RID: 28
        private string Serial;

        // Token: 0x0400001D RID: 29
        private string Port;

        // Token: 0x0400001E RID: 30
        private bool _isApply = false;

        // Token: 0x0400001F RID: 31
        private string _licenseString = "";

        // Token: 0x04000020 RID: 32
        private ActivationType Type;

        // Token: 0x04000021 RID: 33
        private string _fullText;

        // Token: 0x04000022 RID: 34
        private int EdtionLevel = 0;

        // Token: 0x04000023 RID: 35
        private int _orgnum = 0;

        // Token: 0x04000024 RID: 36
        private string _serverDomain = string.Empty;
        private string _ip = string.Empty;

        // Token: 0x04000025 RID: 37
        private int _serverPort = 80;

        // Token: 0x04000026 RID: 38
        private DateTime _initDate;

        // Token: 0x04000027 RID: 39
        private DateTime _AnalysisTime = DateTime.MinValue;

        // Token: 0x04000029 RID: 41
        private License _p;

        // Token: 0x0400002A RID: 42
        private readonly object _syncLock = new object();

        // Token: 0x0400002B RID: 43
        private object o = new object();

        internal string[] LimitDomain = new string[]
        {
            "net", "com", "org", "cn", "me", "site", "co", "cc", "info", "net.cn",
            "com.cn", "org.cn"
        };

        public bool IsAnalysis { get; set; }

        private string[] _level = new string[] { "社区版", "普及版", "基础版", "标准版", "专业版", "旗舰版", "大客户版" };

        public LicenseGenerator(GenerateConfig config)
        {
            _config = config;
            _serverDomain = _config.Domain;
            _serverPort = _config.Port;
        }

        public string EncryptForAscii(string text)
        {
            string ascii = "";
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(text);
                foreach (byte b in bytes)
                {
                    string encryptedByte = (b ^ 15).ToString("D4");
                    ascii += encryptedByte;
                }
            }
            catch
            {
                ascii = null;
            }
            return ascii;
        }

        public string DecryptForAscii(string ascii)
        {
            string text;
            try
            {
                byte[] array = new byte[ascii.Length / 4];
                for (int i = 0; i < ascii.Length; i += 4)
                {
                    array[i / 4] = (byte)(Convert.ToInt32(ascii.Substring(i, 4)) ^ 15);
                }
                text = Encoding.ASCII.GetString(array);
            }
            catch
            {
                text = null;
            }
            return text;
        }


        public bool _initLocalLicense(string lic)
        {
            _licenseString = lic;
            bool flag3 = !string.IsNullOrWhiteSpace(_licenseString);
            if (flag3)
            {
                bool flag4 = _licenseString.IndexOf("=") > -1 && _licenseString.Length > 0;
                if (flag4)
                {
                    _licenseString = _licenseString.Substring(_licenseString.LastIndexOf("=") + 1);
                }
                _licenseString = Regex.Replace(_licenseString, "\\D", "", RegexOptions.Singleline);
            }
            bool flag5 = string.IsNullOrEmpty(_licenseString);
            bool flag6;
            if (flag5)
            {
                var EdtionLevel = 0;
                flag6 = false;
            }
            else
            {
                string text2 = _decrypt(_licenseString);
                try
                {
                    flag6 = _SetInitValue(text2);
                }
                catch (Exception ex)
                {
                    flag6 = false;
                }
            }
            return flag6;

            //_fullText = lic;
            //_licenseString = lic.Split('=')[1];
            //var ret = false;
            //string text2 = _decrypt(_licenseString);
            //try
            //{
            //    ret = _SetInitValue(text2);
            //}
            //catch (Exception ex)
            //{
            //    ret = false;
            //}

            //return ret;
        }

        public string _decrypt(string licenseString)
        {
            var d = Regex.Replace(_licenseString, "\\D", "", RegexOptions.Singleline);
            string text = DecryptForAscii(d);
            bool flag = string.IsNullOrEmpty(text);
            string text2;
            if (flag)
            {
                text2 = "";
            }
            else
            {
                Type = (ActivationType)int.Parse(text.Substring(0, 1));
                string text3 = text.Substring(1);
                string decryptKey = GetDecryptKey(Type);
                text3 = DecryptForDES(text3, decryptKey);
                bool flag2 = string.IsNullOrEmpty(text3);
                if (flag2)
                {
                    text2 = "";
                }
                else
                {
                    text2 = text3;
                }
            }
            return text2;
        }

        public string GetDecryptKey(ActivationType type)
        {
            string text = string.Empty;
            switch (type)
            {
                case ActivationType.CPU:
                    text = CPU_ID;
                    break;
                case ActivationType.HardDisk:
                    text = HardDiskID;
                    break;
                case ActivationType.IP:
                    text = _serverDomain;
                    text = text + ":" + _serverPort;
                    break;
                case ActivationType.Domain:
                    //text = Server.Domain;
                    //text = text + ":" + Server.Port;
                    break;
                case ActivationType.Root:
                    text = _serverDomain + ":" + _serverPort;
                    break;
                default:
                    //text = Server.Domain;
                    //text = text + ":" + Server.Port;
                    break;
            }
            //var PlatformName = _config.PlatformName;
            //var PlatformVersion = _config.PlatformVersion;
            //text = text + PlatformName + PlatformVersion;
            while (text.Length < 8)
            {
                text += text;
            }
            text = new ConvertToAnyValue(text).MD5;
            bool flag = text.Length > 8;
            if (flag)
            {
                text = text.Substring(0, 8);
            }
            return text;
        }
        public string DecryptForDES1(string decryptStr, string decryptKey)
        {
            try
            {
                byte[] array = null;
                byte[] rgbIV = new byte[8] { 18, 52, 86, 120, 144, 171, 205, 239 };
                byte[] array2 = new byte[decryptStr.Length];
                if (decryptKey.Length > 8)
                {
                    decryptKey = decryptKey.Substring(0, 8);
                }

                array = Encoding.UTF8.GetBytes(decryptKey);
                DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                array2 = Convert.FromBase64String(decryptStr);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(array, rgbIV), CryptoStreamMode.Write);
                cryptoStream.Write(array2, 0, array2.Length);
                cryptoStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch
            {
                return null;
            }
        }

        public string DecryptForDES(string decryptStr, string decryptKey)
        {
            string text;
            try
            {
                byte[] array = new byte[] { 18, 52, 86, 120, 144, 171, 205, 239 };
                byte[] bytes = Encoding.UTF8.GetBytes(decryptKey.ToLower());
                DESCryptoServiceProvider descryptoServiceProvider = new DESCryptoServiceProvider();
                byte[] array2 = Convert.FromBase64String(decryptStr);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, descryptoServiceProvider.CreateDecryptor(bytes, array), CryptoStreamMode.Write);
                cryptoStream.Write(array2, 0, array2.Length);
                cryptoStream.FlushFinalBlock();
                Encoding encoding = new UTF8Encoding();
                text = encoding.GetString(memoryStream.ToArray());
            }
            catch (Exception EX)
            {
                text = null;
            }
            return text;
        }

        public string EncryptForDES(string encryptStr, string encryptKey)
        {
            string encryptedText;
            try
            {
                byte[] iv = new byte[] { 18, 52, 86, 120, 144, 171, 205, 239 };
                byte[] inputBytes = Encoding.UTF8.GetBytes(encryptStr);
                byte[] keyBytes = Encoding.UTF8.GetBytes(encryptKey);

                DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider();
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, desCryptoServiceProvider.CreateEncryptor(keyBytes, iv), CryptoStreamMode.Write);

                cryptoStream.Write(inputBytes, 0, inputBytes.Length);
                cryptoStream.FlushFinalBlock();

                encryptedText = Convert.ToBase64String(memoryStream.ToArray());
            }
            catch
            {
                encryptedText = null;
            }

            return encryptedText;
        }

        public string CPU_ID
        {
            get
            {
                string text = null;
                try
                {
                    ManagementClass managementClass = new ManagementClass("win32_Processor");
                    ManagementObjectCollection instances = managementClass.GetInstances();
                    foreach (ManagementBaseObject managementBaseObject in instances)
                    {
                        ManagementObject managementObject = (ManagementObject)managementBaseObject;
                        bool flag = managementObject.Properties["Processorid"] != null;
                        if (flag)
                        {
                            text = managementObject.Properties["Processorid"].Value.ToString();
                            break;
                        }
                    }
                }
                catch
                {
                }
                bool flag2 = string.IsNullOrWhiteSpace(text);
                if (flag2)
                {
                    text = "notGetCPU";
                }
                return text;
            }
        }

        public string HardDiskID
        {
            get
            {
                string text = null;
                try
                {
                    ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                    using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator())
                    {
                        if (enumerator.MoveNext())
                        {
                            ManagementObject managementObject = (ManagementObject)enumerator.Current;
                            text = managementObject["SerialNumber"].ToString().Trim();
                        }
                    }
                }
                catch
                {
                }
                bool flag = string.IsNullOrWhiteSpace(text);
                if (flag)
                {
                    try
                    {
                        ManagementObjectCollection managementObjectCollection = new ManagementObjectSearcher
                        {
                            Query = new SelectQuery("Win32_DiskDrive", "", new string[] { "PNPDeviceID", "Signature" })
                        }.Get();
                        ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = managementObjectCollection.GetEnumerator();
                        enumerator2.MoveNext();
                        ManagementBaseObject managementBaseObject = enumerator2.Current;
                        text = managementBaseObject.Properties["signature"].Value.ToString().Trim();
                    }
                    catch
                    {
                    }
                }
                bool flag2 = string.IsNullOrWhiteSpace(text);
                if (flag2)
                {
                    try
                    {
                        ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
                        ManagementObject managementObject2 = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
                        managementObject2.Get();
                        text = managementObject2.GetPropertyValue("VolumeSerialNumber").ToString();
                    }
                    catch
                    {
                    }
                }
                bool flag3 = string.IsNullOrWhiteSpace(text);
                if (flag3)
                {
                    text = "notGetHardDiskID";
                }
                return text;
            }
        }

        public string RegistCode(int type, string value)
        {
            var PlatformName = _config.PlatformName ?? "study";
            var PlatformVersion = _config.PlatformVersion ?? "2.0";
            value = string.Concat(new string[]
            {
                value,
                "$",
                PlatformName,
                "$",
                PlatformVersion
            });
            byte[] array = new byte[] { 18, 52, 86, 120, 144, 171, 205, 239 };
            string text4;
            try
            {
                string text = Random(8, 6);
                byte[] bytes = Encoding.UTF8.GetBytes(text.ToLower());
                DESCryptoServiceProvider descryptoServiceProvider = new DESCryptoServiceProvider();
                byte[] bytes2 = Encoding.UTF8.GetBytes(value);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, descryptoServiceProvider.CreateEncryptor(bytes, array), CryptoStreamMode.Write);
                cryptoStream.Write(bytes2, 0, bytes2.Length);
                cryptoStream.FlushFinalBlock();
                string text2 = Convert.ToBase64String(memoryStream.ToArray());
                string text3 = "";
                for (int i = 0; i < text2.Length; i++)
                {
                    bool flag = i < text.Length;
                    if (flag)
                    {
                        text3 = text3 + text2.Substring(i, 1) + text.Substring(i, 1);
                    }
                    else
                    {
                        text3 += text2.Substring(i, 1);
                    }
                }
                text4 = type.ToString() + text3;
            }
            catch (Exception ex)
            {
                text4 = ex.Message;
            }
            return text4;
        }

        public string Random(int VcodeNum, int type)
        {
            string text = "0,1,2,3,4,5,6,7,8,9,";
            string text2 = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
            string text3 = text2.ToUpper();
            string text4;
            switch (type)
            {
                case 0:
                    text4 = text + text2 + text3;
                    break;
                case 1:
                    text4 = text;
                    break;
                case 2:
                    text4 = text2;
                    break;
                case 3:
                    text4 = text3;
                    break;
                case 4:
                    text4 = text3 + text2;
                    break;
                case 5:
                    text4 = text + text2;
                    break;
                case 6:
                    text4 = text + text3;
                    break;
                default:
                    text4 = text + text2 + text3;
                    break;
            }
            text4 = text4.Substring(0, text4.Length - 1);
            string[] array = text4.Split(new char[] { ',' });
            string text5 = "";
            Random random = new Random();
            for (int i = 1; i < VcodeNum + 1; i++)
            {
                text5 += array[random.Next(array.Length)];
            }
            return text5;
        }

        private bool _SetInitValue(string licenseString)
        {
            bool flag = false;
            string[] array = (string.IsNullOrWhiteSpace(licenseString) ? null : licenseString.Split(new char[] { ';' }));
            bool flag2 = array == null || array.Length <= 1;
            if (flag2)
            {
                EdtionLevel = 0;
                StartTime = DateTime.MinValue;
                EndTime = DateTime.MaxValue.AddYears(-1);
                Type = ActivationType.IP;
                Serial = "0.0.0.0";
                Port = "80";
            }
            else
            {
                Serial = array[1];
                bool flag3 = Type == ActivationType.Domain || Type == ActivationType.IP || Type == ActivationType.Root;
                if (flag3)
                {
                    bool flag4 = Serial.Length > 0 && Serial.IndexOf(":") > -1;
                    if (flag4)
                    {
                        bool flag5 = !Serial.EndsWith(":");
                        if (flag5)
                        {
                            Port = Serial.Substring(Serial.LastIndexOf(":") + 1);
                        }
                        bool flag6 = !Serial.StartsWith(":");
                        if (flag6)
                        {
                            Serial = Serial.Substring(0, Serial.LastIndexOf(":"));
                        }
                    }
                }
                StartTime = Convert.ToDateTime(array[2]);
                EndTime = Convert.ToDateTime(array[3]);
                int num;
                int.TryParse(array[4], out num);
                EdtionLevel = ((num <= 1) ? 1 : num);
                flag = DateTime.Now > StartTime && DateTime.Now < EndTime.AddDays(1.0);
                bool flag7 = array.Length > 5;
                if (flag7)
                {
                    int.TryParse(array[5], out _orgnum);
                }
                bool flag8 = Type == ActivationType.Root;
                if (flag8)
                {
                    string domain =  _serverDomain;// Server.Domain;
                    bool flag9 = flag && domain.Length < Serial.Length;
                    if (flag9)
                    {
                        flag = false;
                    }
                    bool flag10 = flag && !domain.EndsWith(Serial, StringComparison.CurrentCultureIgnoreCase);
                    if (flag10)
                    {
                        flag = false;
                    }
                    bool flag11 = flag && domain.Length > Serial.Length;
                    if (flag11)
                    {
                        bool flag12 = domain.IndexOf(Serial) > 0;
                        if (flag12)
                        {
                            bool flag13 = domain.Substring(domain.IndexOf(Serial) - 1, 1) != ".";
                            if (flag13)
                            {
                                flag = false;
                            }
                        }
                    }
                    bool flag14 = flag;
                    if (flag14)
                    {
                        foreach (string text in LimitDomain)
                        {
                            bool flag15 = string.Equals(Serial, text, StringComparison.CurrentCultureIgnoreCase);
                            if (flag15)
                            {
                                flag = false;
                                break;
                            }
                        }
                    }
                }
                EdtionLevel = ((!flag) ? 0 : EdtionLevel);
                IsAnalysis = true;
            }
            bool flag16 = flag && EdtionLevel != 0;
            if (flag16)
            {
                IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    HttpRuntime.Cache.Remove(Convert.ToString(enumerator.Key));
                }
            }
            return flag;
        }
    }

    public enum ActivationType
    {
        // Token: 0x0400002D RID: 45
        CPU = 1,
        // Token: 0x0400002E RID: 46
        HardDisk,
        // Token: 0x0400002F RID: 47
        IP,
        // Token: 0x04000030 RID: 48
        Domain,
        // Token: 0x04000031 RID: 49
        Root
    }

    class GenerateConfig
    {
        public string Domain { get; set; }

        public int Port { get; set; }

        public string PlatformName { get; set; }

        public string PlatformVersion { get; set; }

        public string CPU { get; set; }

        public string HardDisk { get; set; }
    }
}
